package netty.protocoltcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * Created by yu756 on 2020/1/9 10:29
 */
public class MyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {
    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocol msg) throws Exception {
     /*   byte[] buffer = new byte[msg.readableBytes()];
        msg.readBytes(buffer);
        System.out.println("客户端接收到消息" + new String(buffer, CharsetUtil.UTF_8));
        System.out.println("服务端接收到信息量" + (++this.count));;*/

        int len = msg.getLen();
        byte[] content = msg.getContent();

        System.out.println("服务端接收到长度" + len);
        System.out.println("服务端接收到长度" + new String(content, CharsetUtil.UTF_8));
        System.out.println("服务端接收到信息量" + (++this.count));
    }
// 重写发送数据


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("MyClientHandler 发送数据");
        for (int i = 0; i < 5; i++) {
            String message = "快回家过年了，高兴";
            byte[] content = message.getBytes(CharsetUtil.UTF_8);
            int length = message.getBytes(CharsetUtil.UTF_8).length;
            // 创建协议包
            MessageProtocol messageProtocol = new MessageProtocol();
            messageProtocol.setLen(length);
            messageProtocol.setContent(content);
            ctx.writeAndFlush(messageProtocol);
        }


    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
